var _CONTEXT_PATH_URL_ = _CONTEXT_PATH_URL_ || 'http://localhost:8080/desktop-web';
var _SSO_SSOServerUrl_;
var _SSO_SSOCenterUrl_;
var _COOKIE_DOMAIN_;
var _COOKIE_ID_;
var _APP_INDEX_URL_;

var LzxCommonHeader = (function($){
	var _this = this;
    // 配置信息
    var config = {
        domain: _CONTEXT_PATH_URL_, // 桌面web项目访问根URL
        containerId: 'header',// 页面元素id
        htmlStr: ' <div id="fix-header" class="fix-header clearfix">    <input type="hidden" id="userinfo_usertype" value="102">		<div class="header-box clearfix w1200">			<a class="jz-logo fl" href="javascript:;"><img src="http://localhost:8080/desktop-web/resources/default/main/images/jz_logo.png" alt=""></a>        	<div class="nav-g-links clearfix" id="nav_g_top_right">        	        		<div class="nav-u-info fn-right g-set" id="nav_g_uinfo_base" style="font-size:12px;">					<a id="nav_user_info_base" href="javascript:;" class="links nav-down">   							金硕						<i class="idesk-ico i-nav-arrows"></i> 					</a>					 <div class="nav-g-dropdown nav-uset-dropdown" id="nav_dropdown_base" style="display: none;">						<ul>							<li>								 <a class="nav-d-set nav-my-info" data-role="user-info" id="nav-personal_set" target="_self" href="javascript:void(0);">设置</a>							</li>							<li>								<a id="logoutBtn" href="javascript:logout(\'http://localhost:8080/desktop-web\');" class="nav-d-set nav-user-logout" data-role="logout">退出</a>							</li>						</ul>					</div>				</div>        					<div class="nav-g-welcome fn-right">					<div class="nav-g-welcome-box">						<span class="l"></span>						<div class="nav-input-wrap">							<span class="txt" id="nav_g_welcome">			   							<span title="锦州十中" style="font-size:12px;">锦州十中</span>							</span>						</div>						<span class="r"></span>					</div>				</div>												<div class="nav-g-links-color fn-left nav-teacher-settings">					<a class="links desktop-txt" href="http://localhost:8080/desktop-web/index.action">						<i class="idesk-ico i-nav-home"></i>首页					</a>					<a class="links desktop-txt" href="http://localhost:8080/desktop-web/desktop.action">						<i class="idesk-ico i-nav-desk"></i>桌面					</a>					<a class="links desktop-txt" href="http://portal.jztest.changyan.cn/init/app.do?url=/open/sso/cloud.do?screen=full&from=ew">						<i class="idesk-ico i-nav-sapp"></i>应用中心					</a>				</div>								<div id="nav-g-message" class="nav-g-links-color nav-g-message fn-left">					<a id="messageCenter" class="links" href="javascript:;" style="width: 70px;">						<i class="idesk-ico i-nav-message"></i>消息					</a>					<div class="nav-g-dropdown nav-message-dropdown" style="display: none;">					</div>				</div>			</div>		</div></div>',// 导航html string
        ssoServerUrl: 'http://open.jztest.changyan.cn/sso',// 区域sso url
        ssoCenterUrl: 'http://test.open.changyan.com/sso',//中心sso url
        messageCenterUrl: 'http://jztest.changyan.cn/message-web/message/index.action', // 消息中心url
        deskTopManageUrl: 'http://portal.jztest.changyan.cn', // 桌面管理url
        cookieDomain: 'http://shuojin.iflytek.com:8080', // 桌面管理url
        fristRole: 'teacher',
        cookieId: '0d06b908-88f2-4bdf-8697-1d32e1611b91',
        appIndexUrl: 'http://jztest.changyan.cn/desktop-web/desktop.action'

    }

   
 // sso 配置
    _SSO_SSOServerUrl_ = config.ssoServerUrl;
    _SSO_SSOCenterUrl_ = config.ssoCenterUrl;
    _COOKIE_DOMAIN_ = config.cookieDomain;
    _COOKIE_ID_ = config.cookieId;
    _APP_INDEX_URL_ = config.appIndexUrl;
    
    //对于cookie中信息与第一进入到页面中的信息是否相同对比，2秒间隔
    window.setInterval(compareRole,2000); 
	function compareRole(){
		if(config.cookieId != "cookie_role_info"){
			var cookieRole = $.cookie(_COOKIE_ID_);
			if(cookieRole != null && cookieRole !="null" && cookieRole != ""){
				if(config.fristRole != cookieRole){
					if(config.appIndexUrl != "null"){
						window.location.href=config.appIndexUrl;
					}else{
						window.location.reload();
					}
				}
			}
		}
	}
    alert(3332);
    // 引入css及js
    //loadjscssfile(config.domain + '/resources/default/nav/css/nav.css', 'css');
    //loadjscssfile(config.domain + '/resources/plugins/js/jquery/html5shiv.js', 'js');
    //loadjscssfile(config.domain + '/resources/plugins/js/jquery/respond.min.js', 'js');
//    showNavHtml();

    /**
     * 显示导航HTML
     */
    _this.showNavHtml = function(){
//        document.getElementById(config.containerId).innerHTML = config.htmlStr;
        
        
        // 执行原本页面上的js
        exePageJS();
    }

    /**
     * 实现对前端字符串进行GET编码的函数
     */
    function appEncodeURL(s){
        var reg = /^[\u0391-\uFFE5%]+$/;
        var urlLength = s.length;
        var newS = "";
        for(var i = 0; i < urlLength; i++) {
            if(reg.test(s.charAt(i))) {
                newS += escape(s.charAt(i));
            }
            else {
                newS += s.charAt(i);
            }
        }
        if(newS.indexOf('_app_encoding_tag_=')== -1){
            if(newS.indexOf('?') >= 0) {
                newS = newS + '&_app_encoding_tag_=1';
            }else{
                newS = newS + '?_app_encoding_tag_=1';
            }
        }
        return encodeURI(newS);
    }

    /**
     * 从页面上拉过来的js，主要是时间绑定
     */
   function exePageJS(){
	   //登录按钮点击出现弹窗
	   try {
	       if(typeof(checkLogin) == "function"){
	    	   jQuery("#btnLogin").attr("href","javascript:checkLogin();");
	       }
	   } catch(e) {
		   
	   }
	   
       /*个人设置与退出鼠标悬浮下拉事件*/
       jQuery("#nav_g_uinfo_base").hover(function() {
    	   jQuery("#nav_dropdown_base").css('display', 'block');
       }, function() {
    	   jQuery("#nav_dropdown_base").css('display', 'none');
       });
       
       /*身份切换鼠标悬浮下拉事件*/
       jQuery("#nav_g_uinfo_role").hover(function() {
    	   jQuery("#nav_dropdown_role").css('display', 'block');
       }, function() {
    	   jQuery("#nav_dropdown_role").css('display', 'none');
       });

       jQuery("#nav-personal_set").attr("href",config.domain + "/personInfo/personalSettings.action");
       
       jQuery("#nav-bind_info").attr("href",config.domain + "/bind/mainBind.action");
       
       jQuery("#nav-g-message #messageCenter").attr('href',config.messageCenterUrl);
       
       if(jQuery('#nav-personal_set').length > 0){
    	   refreshMessage()
           setInterval(function(){refreshMessage()}, 60000);
       }

       /*应用中心鼠标悬浮下拉事件*/
       jQuery(".nav-g-app-center").hover(function(){
    	   jQuery(".app-center-dropdown").css('display','block');
       },function(){
    	   jQuery(".app-center-dropdown").css('display','none');
       });

       /*云导航应用鼠标悬浮下拉时间*/
       jQuery(".navbar-app").hover(function(){
    	   jQuery(".cloud-app-dropdown").css('display','block');
       },function(){
    	   jQuery(".cloud-app-dropdown").css('display','none');
       });
       
       /*系统应用鼠标悬浮下拉事件*/
       jQuery(".nav-g-sys-app").hover(function() {
           jQuery(".sys-app-dropdown").css('display', 'block');
       }, function() {
           jQuery(".sys-app-dropdown").css('display', 'none');
       });

       /*个人应用鼠标悬浮下拉事件*/
       jQuery(".nav-g-personal-app").hover(function() {
           jQuery(".personal-app-dropdown").css('display', 'block');
       }, function() {
           jQuery(".personal-app-dropdown").css('display', 'none');
       });
       
	   //登录按钮点击出现弹窗
	   $("#btnLogin").click(function(){
		   var url = location.protocol + "//" + location.hostname + ((location.port == '') ? ":80" : location.port) + location.pathname;
		   if (url.indexOf(_CONTEXT_PATH_URL_ + '/index.action') >= 0 || url.indexOf(_CONTEXT_PATH_URL_ + '/login.action') >= 0) {
			   $("#popLogin").zxxbox({fix:true});
		   } else {
			   window.location.href = _CONTEXT_PATH_URL_ + '/login.action?popLogin=pop';
		   }
	   });
	   //
	   $(".r-arrows").click(function(){
		   $(this).toggleClass("up");
	   });
       
   }
   
   function refreshMessage(){
	   jQuery.ajax({
		   type:"get",
		   url:config.domain + '/nav/getMessageTypeAndCount.action',
		   dataType:"jsonp",/*加上datatype*/
		   jsonpCallback:"callback",
		   success: function(data){
			   var unreadMsg = 0;
	           var msgHtml = "<ul>";
	           var url="";
	           jQuery.each(data, function(i, ele){
	               unreadMsg += ele.count;
	               url = appEncodeURL(config.messageCenterUrl +'?type=' + ele.id);
	               msgHtml += '<li><a href="'+url+'" class="d-app top-a" >'+ele.typeCn;
	               if(ele.count>0){
	            	   if(ele.count > 99){
	            		   ele.count = '99+';
	            	   }
	                   msgHtml += '<i class="unread-msg-num unread-msg-more">'+ ele.count +'</i>';
	               }
	               msgHtml += '</a></li>';
	           });

	           if(msgHtml != '<ul>'){
	               msgHtml += '</ul>';
	               jQuery('.nav-message-dropdown').html(msgHtml);

	               /*消息栏鼠标悬浮下拉事件*/
	               jQuery("#nav-g-message").hover(function() {
	                   jQuery(".nav-message-dropdown").css('display', 'block');
	               }, function() {
	                   jQuery(".nav-message-dropdown").css('display', 'none');
	               });
	           }

	           if(unreadMsg > 0){
	        	   if(jQuery('#messageCenter').children('.unread-msg-num').length == 0){
	        		   if(unreadMsg > 99){
	                       jQuery("#messageCenter").append('<i class="unread-msg-num unread-msg-more">99+</i>');
	                   }else{
	                       jQuery("#messageCenter").append('<i class="unread-msg-num">'+unreadMsg+'</i>');
	                   }
	        	   }else{
	        		   if(unreadMsg > 99){
	                       jQuery("#messageCenter .unread-msg-num").html('99+');
	                   }else{
	                	   jQuery("#messageCenter .unread-msg-num").html(unreadMsg);
	                   }
	        	   }
	           }
		   }
	   });
   }
   
    /**
     * 动态引入js或css
     */
    function loadjscssfile(filename,filetype){
        if(filetype == "js"){
            var fileref = document.createElement('script');
            fileref.setAttribute("type","text/javascript");
            fileref.setAttribute("src",filename);
        }else if(filetype == "css"){

            var fileref = document.createElement('link');
            fileref.setAttribute("rel","stylesheet");
            fileref.setAttribute("type","text/css");
            fileref.setAttribute("href",filename);
            fileref.setAttribute("onload","javascript:LzxCommonHeader.showNavHtml()");
        }
        if(typeof fileref != "undefined"){
            document.getElementsByTagName("head")[0].appendChild(fileref);
        }
    }
    
    if (top.location !== self.location) {
		top.location=self.location;
	}
    
    return _this;
})(jQuery);


function logout(gotoPageUrl){
    var logoutURL = _SSO_SSOServerUrl_ + "/logout";
    jQuery.ajax({
        url: logoutURL,
        type: "GET",
        dataType: "jsonp",
        jsonp: "callback",
        crossDomain: true,
        cache: false,
        success: function(html) {
            html = jQuery.trim(html).replace(/\t/g, "");
            var resultobj = evalJSON(html);
            if (resultobj.result && resultobj.result == "success") {
                logoutOtherPT(gotoPageUrl);
            }
        },
        error: function(data) {
            var resultobj = {
                result: "fail",
                code: "-1",
                data: "退出失败"
            };
            logoutOtherPT(gotoPageUrl);
        }
    });
    
    jQuery.ajax({
        url: _SSO_SSOCenterUrl_ + "/logout",
        type: "GET",
        dataType: "jsonp",
        jsonp: "callback",
        crossDomain: true,
        cache: false,
        success: function(html) {
        },
        error: function(data) {
        }
    });
}

/**
 * 切换角色
 * @param obj
 */
function changeRole(obj){
	var getChangeRoleUrlAction = _CONTEXT_PATH_URL_+'/changeRole.action?role=' + obj;
	$.ajax({
		    type: "get",
		    async: false,
		  dataType:"jsonp", 
		 jsonp: "callbackparam",
		    url: getChangeRoleUrlAction,
		   	success: function(data){
				if($.cookie(_COOKIE_ID_)==null || $.cookie(_COOKIE_ID_) =="" || $.cookie(_COOKIE_ID_) =="null"){
					$.cookie(_COOKIE_ID_, obj, {expires: 1, path: '/', domain:_COOKIE_DOMAIN_});
				}
				if(_APP_INDEX_URL_ != "null"){
					window.location.href=_APP_INDEX_URL_;
				}else{
					window.location.reload();
				}
			}
		});
}

function evalJSON(s) {
    return eval("(" + s + ")")
}

/**
 * 退出其他子应用
 */
function logoutOtherPT(gotoPageUrl){
    var getLogoutUrlAction = _CONTEXT_PATH_URL_+'/logoutUrlList.action';

    // 这里使用jsonp是因为导航头会有其他子系统引用，解决子系统调用问题
    jQuery.ajax({
        url:getLogoutUrlAction,
        type:"get",
        dataType:"jsonp",
        jsonp: "logoutCallbackParam",
        success:function(data){
            for(var logourUrl in data){
                jQuery.ajax({
                    url: data[logourUrl],
                    type:"get",
                    dataType:"jsonp"
                });
            }
            setTimeout(function() {
                window.location.href=gotoPageUrl;
            }, 100);
        }
    });
}